const Koa = require('koa');
const Router = require('koa-router');
const path = require('path');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const CONFIG = require('./config/index');
const errorHandle = require('./middlewares/errorHandle');

const static = require('koa-static');
const render = require('koa-art-template');
const koajwt = require('koa-jwt'); //用于验证token


const app = new Koa();
const router = new Router()

const db = require('./config/db');

app.use(bodyParser());

app.keys = ['some secret hurr'];

// session使用
app.use(session(CONFIG.sessionConfig, app));

// 静态资源
app.use(static(
    path.join( __dirname,  'public')
)) 
// art-template模板引擎
render(app, {
    root: path.join(__dirname, 'views'),
    extname: '.html',
    debug: process.env.NODE_ENV !== 'production'
});
// 错误处理
app.use(errorHandle)
// 使用koa-jwt进行路由权限验证
/* unless 指定哪些 URL 不需要进行 token 验证 */
// app.use(koajwt({secret:CONFIG.secret}).unless({path:[/\/login/,/\/register/]}))

// 装载所有路由 
router.use('/admin', require('./router/admin/api/admin'))
// 登陆 注册
router.use('/register', require('./router/admin/api/register'))
router.use('/login', require('./router/admin/api/login'))
// 前端页面
router.use('/', require('./router/index'))
router.use('/article', require('./router/article'))
router.use('/about', require('./router/about'))

app.listen(3000, () => {
    console.log('Server run at port:3000');
})

app.use(router.routes())
    .use(router.allowedMethods());